package server

import (
	"encoding/hex"
	"fmt"
	"net"
	"os"
	"strconv"
	"unionPay/iso8583"
)

//ServListen 服务监听
type ServListen struct {
	Port string
}

// New 创建服务监听程序
func New(port string) *ServListen {
	return &ServListen{Port: port}
}

//Serv 启动服务监听地址
func (sl *ServListen) Serv() {
	port := fmt.Sprintf(":%s", sl.Port)
	fmt.Println("port:", sl.Port)
	//生成TCP地址链接
	tcpAddr, err := net.ResolveTCPAddr("tcp4", port)
	if err != nil {
		fmt.Printf("监听端口出现错误:%s", err)
		os.Exit(0)
	}
	//监听端口
	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		fmt.Printf("监听端口出现错误:%s", err)
		os.Exit(0)
	}

	for {
		conn, err := listener.AcceptTCP()
		if err != nil {
			fmt.Printf("监听端口出现错误:%s", err)
			continue
		}
		fmt.Println("服务端的链接：", conn)
		//conn.Close()
		go handler(conn)

	}
}
func handler(conn *net.TCPConn) {

	defer conn.Close() // close connection before exit
	for {
		request := make([]byte, 1024)
		len, err := conn.Read(request)
		if err != nil {
			fmt.Println(err)
			break
		}
		if len == 0 {
			fmt.Println(0)
		} else {
			data := hex.EncodeToString(request)
			fmt.Println(data)
			//根据报文头进行解析报文长度
			size := request[:4]
			if "0000" == string(size) {
				continue
			}
			if strLen, err := strconv.Atoi(string(size)); err == nil {
				dist := make([]byte, strLen)
				copy(dist, request[4:4+strLen])
				message := iso8583.NewMessage()
				message.Do(dist)
				conn.Write(dist)
			} else {
				fmt.Printf("解析域出现错误：%+v\n\t", err.Error())
			}

		}

	}
}
